package com.gopay.scheduler.job;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.gopay.common.constants.trans.TxnStaCode;
import com.gopay.common.cps.dao.order.CpsGeneralMainOrderQueryDAO;
import com.gopay.common.exception.GopayException;
import com.gopay.remote.order.MainOrderField;
import com.gopay.remote.order.MainOrderUpdateRemoteService;
import com.gopay.scheduler.GopayBaseJob;

/**
 * 手工调账超时任务
 * 
 * 将非当天的[手工调账]订单标记为[失效]
 * 
 * @CheckTimeoutManualAdjustJob.java
 * @author yaobo
 * @2014-3-18 下午03:44:49 www.gopay.com.cn Inc.All rights reserved.
 */
public class CheckTimeoutManualAdjustJob extends GopayBaseJob {
    private Logger logger = LoggerFactory.getLogger(CheckTimeoutOrderJob.class);

    /* IOC注入方法开始 */
    private CpsGeneralMainOrderQueryDAO cpsGeneralMainOrderDAO;
    private MainOrderUpdateRemoteService cpsGeneralMainOrderOperClient;

    @Override
    public void doJobInternal() {
        
        // 根据超时时间清理除银行订单以外的超时订单

        int count =cpsGeneralMainOrderDAO.findTimeoutManualAdjustCount();
		if(count==0){
			logger.info("found" + count + " Other orders overtime record, not for processing");
			return;
		}
		//循环次数
		int i = (count+999)/1000;
		for (int j = 0; j < i; j++) {
			//每次1000条
			List<Object> orderList = cpsGeneralMainOrderDAO
					.findTimeoutManualAdjust(j*1000+1,1000);
			updateStatus(orderList);
		}
       
    }

    private void updateStatus(List<Object> orders) {
    	 logger.info("found " + orders.size() + " other orders  records, overtime timeout order clean-up work now!");
         Map<MainOrderField, String> map = new HashMap<MainOrderField, String>();

         String txnStaCode = String.valueOf(TxnStaCode.TXN_STA_CD_20002.value);

         map.put(MainOrderField.TXN_STA_CD, txnStaCode);
         SimpleDateFormat sf = new SimpleDateFormat("yyyyMMddHHmmss");
         map.put(MainOrderField.TRAN_FINISH_TIME, sf.format(new Date()));

         for (Object obj : orders) {
             String gopayOrderId = String.valueOf(obj);
             try {
                 cpsGeneralMainOrderOperClient.updateMany(gopayOrderId, map);
             } catch (GopayException e) {
                 logger.error(e.printErrMsg());
             }
         }
	}

	@Resource(name = "cpsGeneralMainOrderOperClient")
    public void setCpsGeneralMainOrderOperClient(MainOrderUpdateRemoteService cpsGeneralMainOrderOperClient) {
        this.cpsGeneralMainOrderOperClient = cpsGeneralMainOrderOperClient;
    }

    @Resource(name = "cpsGeneralMainOrderDAO")
    public void setCpsGeneralMainOrderDAO(CpsGeneralMainOrderQueryDAO cpsGeneralMainOrderDAO) {
        this.cpsGeneralMainOrderDAO = cpsGeneralMainOrderDAO;
    }

}
